package com.cd826dong.clouddemo.redis.repository;

import com.cd826dong.clouddemo.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;

@Repository
public class UserRedisRepository {
    public static final String USER_KEY_PRE = "user:";

    @Autowired
    @Qualifier("userRedisTemplate")
    private RedisTemplate<String, String> userRedisTemplate;

    private ValueOperations<String, String> operations;

    @PostConstruct
    private void init(){
        this.operations = userRedisTemplate.opsForValue();
    }

    public void saveUser(String string){
        operations.set(buildKey(string), string);
    }

    public String findOne(String userId){
        String key = buildKey(userId);
//        if(userRedisTemplate.hasKey(key)){
//            return null;
//        }

        return operations.get(key);
    }

    /**
     * 删除
     * @param userId
     */
    public void delete(String userId) {
        this.userRedisTemplate.delete(this.buildKey(userId));
    }



    /**
     * 构造存储的Key
     * @param userId
     * @return
     */
    protected String buildKey(String userId) {
        return USER_KEY_PRE + String.valueOf(userId);
    }
}
